#!/usr/bin/env python 
# -*- coding:utf-8 -*-

import time
import json
import ruamel.yaml as yaml
from logger import logger
from dingTalk.dingTalkMessage import jdjc
from db.query import MySQLBase, InfluxBase
from dingTalk.sendDingTalk import DingTalkAPI


class TableStatus:
    def __init__(self):
        self.mysql = MySQLBase()
        self.dta = DingTalkAPI()

    def getTableRowsList(self, db):
        """
        get the table name from mysql
        :return: list
        """
        logger.info("获取数据库节点{}的表名称。".format(db['host']))
        sql_str = """
        select
          @@hostname,
          table_schema,
          table_name,
          ifnull(table_rows,0),
          ifnull(data_length,0),
          ifnull(index_length,0)
        from 
          information_schema.tables
        where 
          table_schema NOT IN (
            'mysql',
            'information_schema',
            'performance_schema',
            'sys',
            'mysql_innodb_cluster_metadata');
        """
        res = self.mysql.query(db, sql_str)
        if res == 0:
            logger.warning("发送钉钉信息：MySQL查询失败")
            nowtime = time.strftime("%Y-%m-%d %H:%M:%S")
            self.dta.dingtalk("{}节点获取表信息失败。{}".format(db['host'], nowtime))
            logger.info("钉钉发送成功")
        else:
            return res


class DataToInflux:
    def __init__(self):
        """class init"""
        self.dta = DingTalkAPI()
        ys = yaml.load(open('./conf/dbinfo.yaml', 'r').read(), Loader=yaml.Loader)
        self.influx = InfluxBase(ys['DBDIC_INFO']['influxdb'])

    def sendDataToInflux(self, points):
        """
        Push data to influxdb
        :param points: Json
        """
        logger.info("将数据写入influx")
        logger.info(points)
        res = self.influx.insert(points)
        if res == 1:
            logger.info("influx数据写入成功")
        else:
            logger.info("发送钉钉信息：influx写入失败")
            nowtime = time.strftime("%Y-%m-%d %H:%M:%S")
            # self.dta.dingtalk(jdjc.format("influx写入失败。", nowtime))
            logger.info("钉钉发送成功")
            exit(1)

    @staticmethod
    def setInfluxData(data):
        """
        # create database and retention policy for your data
        CREATE DATABASE "mysql_innodb_cluster"
        CREATE RETENTION POLICY "mysql_info_schema" ON "innodb_cluster" DURATION 730d REPLICATION 1 DEFAULT

        :param data: the data from mysql
        """
        logger.info("开始组合influx数据")
        metric = "mysql_table"
        nowtime = int(time.time())
        series = []
        for row in data:
            pointValues = {
                "time": nowtime,
                "measurement": metric,
                "tags": {
                    "server": row[0],
                    "database_name": row[1],
                    "table_name": row[2]
                },
                "fields": {
                    "table_rows": row[3],
                    "data_length": row[4],
                    "index_length": row[5]
                }
            }
            series.append(pointValues)
        logger.info("数据组装完成")
        return series
